import os
import re
import logging
import sys
import email
import mailfetch
from django.core.management import setup_environ
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings




class Parser():
    """
    This class is what does all the text processing for the emails received, and then it turns them into tickets.
    """

    mailfetcher = mailfetch.MailFetcher()
    logfile = settings.DAEMON_LOGFILE
    re_string = settings.PARSER_REGEX_STRING
    emailrecords = {}
    current_record = {}
    re = re.compile(re_string)
    
    #LOGGING
    logging.basicConfig(filename=logfile, format='[%(asctime)s]: %(message)s', level=logging.DEBUG, datefmt="%m/%d/%Y %I:%M:%S %p")
    logger = logging.getLogger('tqd.log')
    logger.propagate = True


    def parse_email(self, emailrecord):
        """
        parse email record and turn it into a ticket record to store in the database.
        """
        email_record = self.emailrecords[emailrecord]
        raw_email = email_record.decode('utf-8')
        email_message = email.message_from_string(raw_email)
        for part in email_message.walk():
            print part
            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True)
                self.current_record['body'] = body
                self.logger.info(body)
        email_text = email_record.split('\n')
        
        self.logger.info("Beginning mail parsing operations.")
        for line in email_text:
            self.regex_search(line.strip())
            self.logger.info("%s" % self.current_record)

    def regex_search(self, string):
        """
        regex grab pieces of email and send it to current_record dictionary.
        """
        m = self.re.search(string)
        if m is not None:
            if "From:" in m.string:
                self.current_record['from'] = m.group(2)
            elif 'To:' in m.string:
                self.current_record['to'] = m.group(1)
            elif 'Date:' in m.string:
                self.current_record['date_received'] = m.string.split(':')[1]
            elif 'Message-ID' in m.string:
                self.current_record['message-id'] = m.string.split(':')[1]
            elif 'Subject:' in m.string:
                self.current_record['subject'] = m.string.lstrip('Subject:')
            
             
        
        
